<?php
/**
 * 各种编号生成序列
 * 编号格式: {前缀}YYMMDD{三位序列}
 */
class Sno
{
	/**
	 * 输入前缀，生成编号
	 */
	public static function gen($prx)
	{
		$prx	= strtoupper($prx);
		$ym		= date('Ym');
		$num	= 1;

		$sr		= self::get($prx);
		if($sr) {
			if($ym == $sr['ym']) {
				$num = intval($sr['num'])+1;
			}
			self::update($prx, $ym, $num);
		}
		else {
			self::add($prx, $ym, $num);
		}
		
		return sprintf('%s%d%03d', $prx, $ym, $num);
	}
	
	/**
	 * 输入常量，生成编号；常量见conf/sno.php
	 */
	public static function cgen($key){
		return self::gen(app_cfg('sno', $key));
	}

	protected static function get($prx){
		return Db::get('Sno')->select()->where(array('prx'=>$prx))->getOne();
	}

	protected static function update($prx, $ym, $num){
		return Db::get('Sno')->update(array('ym'=>$ym, 'num'=>$num))->where(array('prx'=>$prx))->exec();
	}

	protected static function add($prx, $ym, $num){
		return Db::get('Sno')->insert(array('prx'=>$prx, 'ym'=>$ym, 'num'=>$num))->exec();
	}

}

?>